<?php
/**
 * Description of CompraDAO
 *
 * @author Magno
 */
class CompraDAO {

    private $conexao;
    private $statusDAO;
    private $clienteDAO;
    private $pacoteLanceDAO;

    public function __construct() {
        $this->conexao = Conexao::getConexao();
        $this->statusDAO = new StatusDAO();
        $this->clienteDAO = new ClienteDAO();
        $this->pacoteLanceDAO = new PacoteLanceDAO();
    }

    public function salvar($compra) {

        try {

            if ($compra->getCompraID() != null && $compra->getCompraID() > 0) {

                $statment = $this->conexao->prepare("UPDATE compra SET
                        valor = :valor,
                        pacoteLanceID = :pacoteLanceID,
                        usuarioID = :usuarioID,
                        statusID = :statusID
                        WHERE compraID = :compraID");
            } else {

                $ip = $_SERVER['REMOTE_ADDR'];

                $statment = $this->conexao->prepare("INSERT INTO compra(compraID,valor,ip,pacoteLanceID,usuarioID,statusID)
                    VALUES (:compraID,:valor,'$ip',:pacoteLanceID,:usuarioID,:statusID);");
            }

            if ($statment->execute($compra->toBD())) {

                if ($compra->getCompraID() == null || $compra->getCompraID() <= 0)
                    $compra->setCompraID($this->conexao->lastInsertId());
                return $compra;
            }else {
                $erros = $statment->errorInfo();
                throw new Exception("Erro CompraDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro CompraDAO:" . $err->getMessage());
        }
    }

    public function excluir($compraID) {

        try {

            $statment = $this->conexao->prepare("DELETE FROM compra WHERE compraID = :compraID");
            $statment->bindParam(':compraID', $compraID);

            if (!$statment->execute()) {
                $erros = $statment->errorInfo();
                throw new Exception("Erro CompraDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro CompraDAO:" . $err->getMessage());
        }
    }

    public function listar($pagina = 0, $pacoteLanceID = -1, $usuarioID = -1, $statusID = -1, $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina);
            $where = $this->getWhere($pacoteLanceID, $usuarioID, $statusID);
            $compras = array();
            $statment = $this->conexao->query("SELECT * FROM compra u $where $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $compra = new CompraBean($row['compraID'], $row['data'], $row['ip'], $row['valor']);
                $compra->setStatus($this->statusDAO->buscarPorID($row['statusID']));

                if($carregarDependencias){
                    $compra->setCliente($this->clienteDAO->buscarPorID($row['usuarioID']));
                    $compra->setPacoteLance($this->pacoteLanceDAO->buscarPorID($row['pacoteLanceID']));
                }

                $compras[] =  $compra;
            }

            return $compras;
        } catch (PDOException $err) {
            throw new Exception("Erro CompraDAO:" . $err->getMessage());
        }
    }

    public function listarPorOrdem($pagina = 0, $tamanho = 0, $ordem = "compraID", $direcao = "ASC", $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina,$tamanho);
            $compras = array();
            $statment = $this->conexao->query("SELECT * FROM compra u ORDER BY u.$ordem $direcao $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $compra = new CompraBean($row['compraID'], $row['data'], $row['ip'], $row['valor']);
                $compra->setStatus($this->statusDAO->buscarPorID($row['statusID']));

                if($carregarDependencias){
                    $compra->setCliente ($this->clienteDAO->buscarPorID($row['usuarioID']));
                    $compra->setPacoteLance($this->pacoteLanceDAO->buscarPorID($row['pacoteLanceID']));
                }

                $compras[] = $compra;
            }

            return $compras;
        } catch (PDOException $err) {
            throw new Exception("Erro CompraDAO:" . $err->getMessage());
        }
    }

    public function buscarPorID($compraID, $carregarDependencias = false) {
        try {

            $row = $this->conexao->query("SELECT * FROM compra WHERE compraID = $compraID ")->fetch(PDO::FETCH_SERIALIZE);

            if (isset ($row['compraID']) && $row['compraID'] > 0) {
                $compra = new CompraBean($row['compraID'], $row['data'], $row['ip'], $row['valor']);
                $compra->setStatus($this->statusDAO->buscarPorID($row['statusID']));

                if($carregarDependencias){
                    $compra->setCliente($this->clienteDAO->buscarPorID($row['usuarioID']));
                    $compra->setPacoteLance($this->pacoteLanceDAO->buscarPorID($row['pacoteLanceID']));
                }
                return $compra;
            } else {
                return null;
            }
        } catch (PDOException $err) {
            throw new Exception("Erro CompraDAO:" . $err->getMessage());
        }
    }

    private function getWhere($pacoteLanceID = -1, $usuarioID = -1, $statusID = -1) {

        $where = " WHERE 1 = 1 ";

        if (isset($pacoteLanceID) && $pacoteLanceID > 0) {
            $where = $where . " AND u.pacoteLanceID = $pacoteLanceID ";
        }

        if (isset($usuarioID) && $usuarioID > 0) {
            $where = $where . " AND u.usuario = $usuarioID ";
        }

        if (isset($statusID) && $statusID > 0) {
            $where = $where . " AND u.statusID = $statusID ";
        }

        return $where;
    }

    public function total($pacoteLanceID = -1, $usuarioID = -1, $statusID = -1) {
        try {

            $where = $this->getWhere($pacoteLanceID, $usuarioID, $statusID);
            $total = $this->conexao->query("SELECT COUNT(u.compraID) total FROM compra u $where")->fetch(PDO::FETCH_COLUMN);
            return $total;
        } catch (PDOException $err) {
            throw new Exception("Erro CompraDAO:" . $err->getMessage());
        }
    }

}
?>